package com.ruoyi.web.controller.jy;

import com.google.gson.Gson;
import com.ruoyi.common.utils.reids.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Timer;
import java.util.TimerTask;

public class WebSocketHandler extends TextWebSocketHandler {

    // 创建一个定时器，每秒向前端推送一次数据
    private Timer timer = new Timer();
    private WebSocketSession session;

    public WebSocketHandler(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    private RedisUtils redisUtils;

    Gson gson = new Gson();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
        startSendingData();
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 这里可以根据前端传来的消息进行处理，暂时不需要处理
    }

    private void startSendingData() {

        // 每秒推送一次数据
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (session != null && session.isOpen()) {
                    try {
                        Object data = redisUtils.get("basicPrice");
                        // 发送 JSON 数据给前端
                        session.sendMessage(new TextMessage(data.toString()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 0, 1000);  // 每秒执行一次
    }
}
